<template>
  <div class="page-container">
    <el-row>
      <!--工具栏-->
      <div class="toolbar">
        <el-form :inline="true" :model="filters" :size="size">
          <el-row class="search-input">
            <el-form-item prop="code" label="请输入订单编号：">
              <el-input v-model="filters.orderNo" placeholder="请输入订单编号"></el-input>
            </el-form-item>
          </el-row>
          <el-row class="search-button button20">
            <el-form-item>
              <kt-button
                icon="fa fa-search"
                :label="$t('action.search')"
                type="primary"
                @click="findPage(null)"
              />
            </el-form-item>
            <el-form-item>
              <kt-button
                icon="fa fa-refresh"
                :label="$t('action.reset')"
                type="primary"
                @click="resetForm('filters')"
              />
            </el-form-item>
            <el-form-item>
              <kt-button icon="fa fa-plus" label="发布" type="primary" @click="handleAdd"/>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </el-row>
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="求购大厅" name="first">
        <el-table
          :data="pageResult"
          ref="multipleTable"
          :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
          style="width: 100%"
        >
          <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="productNum" label="发布数量"></el-table-column>
          <el-table-column prop="productPrice" label="发布总价格"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button @click="sell(scope.row)" type="primary" size="small">卖给他</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="toolbar" style="padding:10px;">
          <el-pagination
            layout="total, prev, pager, next, jumper,sizes"
            @current-change="refreshPageRequest"
            @size-change="handleSizeChange"
            :current-page="pageRequest.pageNum"
            :page-size="pageRequest.pageSize"
            :total="totalSize"
            style="float:right;"
            :page-sizes="[10, 20, 30, 40]"
          ></el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="卖场大厅" name="second">
        <el-table
          :data="pageResult"
          ref="multipleTable"
          :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
          style="width: 100%"
        >
          <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="productNum" label="发布数量"></el-table-column>
          <el-table-column prop="productPrice" label="发布价格"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button @click="buy(scope.row)" type="primary" size="small">购买</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="toolbar" style="padding:10px;">
          <el-pagination
            layout="total, prev, pager, next, jumper,sizes"
            @current-change="refreshPageRequest"
            @size-change="handleSizeChange"
            :current-page="pageRequest.pageNum"
            :page-size="pageRequest.pageSize"
            :total="totalSize"
            style="float:right;"
            :page-sizes="[10, 20, 30, 40]"
          ></el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="我的大厅" name="third">
        <el-table
          :data="pageResult1"
          ref="multipleTable"
          :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
          style="width: 100%"
        >
          <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="buyName" label="买家名称"></el-table-column>
          <el-table-column prop="buyPrice" label="买家价格"></el-table-column>
          <el-table-column prop="sellName" label="卖家名称"></el-table-column>
          <el-table-column prop="sellPrice" label="卖家价格"></el-table-column>
          <el-table-column prop="type" label="交易类型" :formatter="formatterType"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button @click="examine(scope.row)" type="primary" size="small">审核</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="toolbar" style="padding:10px;">
          <el-pagination
            layout="total, prev, pager, next, jumper,sizes"
            @current-change="refreshPageRequest"
            @size-change="handleSizeChange"
            :current-page="pageRequest1.pageNum"
            :page-size="pageRequest1.pageSize"
            :total="totalSize1"
            style="float:right;"
            :page-sizes="[10, 20, 30, 40]"
          ></el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!--发布详情-->
    <el-dialog
      title="发布"
      width="60%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="100px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-row class="searchDialog-input">
            <el-form-item label="发布类型：" prop="type">
          <el-select v-model="dataForm.type" placeholder="请选择发布类型" style="width: 25%">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号：" prop="orderNo">
          <el-input
            v-model="dataForm.orderNo"
            @blur.prevent="changeOrder"
            style="width: 25%"
            placeholder="请输入订单编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品明细：">
          <el-table
            :data="tableProductData"
            style="width: 100%"
            :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
          >
            <el-table-column prop="date" label="商品主图" width="150">
              <template slot-scope="scope">
                <img :src="scope.row.goodsImgUrl" style="width: 60px;height: 60px">
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="商品名称" width="500px"></el-table-column>
            <el-table-column prop="goodsNum" label="订购数量" width="100"></el-table-column>
            <el-table-column prop="buyUnitPrice" width="150" label="购买单价	">
              <template slot-scope="scope">
                <el-input v-model="scope.row.buyUnitPrice" placeholder="请输入购买单价"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button :size="size" @click.native="editDialogVisible = false">{{ $t("action.cancel") }}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >{{ $t("action.submit") }}</el-button>
      </div>
    </el-dialog>
    <!--买卖处理-->
    <el-dialog
      title="买卖处理"
      width="70%"
      :visible.sync="sellBuyDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="sellBuyForm"
        label-width="80px"
        :rules="sellBuyFormRules"
        ref="sellBuyForm"
        :size="size"
      >
        <el-form-item prop="buyId" v-if="false">
          <el-input
            v-model="sellBuyForm.buyId"
            :disabled="true"
            label-width="80px"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="sellId" v-if="false">
          <el-input
            v-model="sellBuyForm.sellId"
            :disabled="true"
            label-width="80px"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品明细">
          <el-table
            :data="tableSellBuyData"
            style="width: 100%"
            :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
          >
            <el-table-column prop="date" label="商品主图" width="150">
              <template slot-scope="scope">
                <img :src="scope.row.goodsImgUrl" style="width: 60px;height: 60px">
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="商品名称" width="500px"></el-table-column>
            <el-table-column prop="goodsNum" label="订购数量" width="100"></el-table-column>
            <el-table-column prop="sellPrice" v-if="activeName== 'first'" width="150" label="卖家价格	">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sellPrice" placeholder="请输入购买单价"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="sellPrice" v-else width="150" label="卖家价格	"></el-table-column>
            <el-table-column v-if="activeName== 'first'" prop="buyPrice" width="150" label="买家价格	"></el-table-column>
            <el-table-column v-else prop="buyPrice" width="150" label="买家价格	">
              <template slot-scope="scope">
                <el-input v-model="scope.row.buyPrice" placeholder="请输入购买单价"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button
          :size="size"
          @click.native="sellBuyDialogVisible = false"
        >{{ $t("action.cancel") }}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click="submitSellBuyForm"
          :loading="editLoading"
        >{{ $t("action.submit") }}</el-button>
      </div>
    </el-dialog>
    <!--审核-->
    <el-dialog
      title="买卖处理"
      width="30%"
      :visible.sync="examineDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="examineForm" label-width="80px" ref="examineForm" :size="size">
        <el-form-item prop="status" label="审核">
          <el-select v-model="examineForm.status" style="width: 25%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button
          :size="size"
          @click.native="examineDialogVisible = false"
        >{{ $t("action.cancel") }}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click="submitExamineForm"
          :loading="editLoading"
        >{{ $t("action.submit") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CyTable from "@/views/Core/ProductTable";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";

export default {
  components: {
    KtButton,
    CyTable,
    TableColumnFilterDialog
  },
  data() {
    return {
      tableSellBuyData: [],
      typeOptions: [
        { value: "1", label: "购买" },
        { value: "2", label: "卖出" }
      ],
      statusOptions: [
        { value: "2", label: "审核通过" },
        { value: "3", label: "审核拒绝" }
      ],
      tableProductData: [],
      orderOptions: [],
      filters: {
        orderNo: "",
        type: "1"
      },
      activeName: "first",
      size: "small",
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: [],
      totalSize: 0,
      pageRequest1: { pageNum: 1, pageSize: 10 },
      pageResult1: [],
      totalSize1: 0,
      editLoading: false,
      editDialogVisible: false, // 新增编辑界面是否显示
      sellBuyDialogVisible: false, //买卖弹框
      examineDialogVisible: false,
      dataFormRules: {
        orderNo: [
          { required: true, message: "请输入订单编号", trigger: "change" }
        ],
        type: [{ required: true, message: "请选择发布类型", trigger: "change" }]
      },
      dataForm: {
        orderNo: "",
        type: ""
      },
      sellBuyForm: {
        orderNo: "",
        buyId: "",
        sellId: ""
      },
      sellBuyFormRules: {},
      examineForm: {
        status: "2",
        id: ""
      }
    };
  },
  mounted() {
    this.findPage();
  },
  methods: {
    submitExamineForm: function() {
      let this_ = this;
      this_.$refs.examineForm.validate(valid => {
        if (valid) {
          this_.$confirm("确认提交吗？", "提示", {}).then(() => {
            this_.editLoading = true;
            let params = {};
            params.id = this_.examineForm.id;
            params.status = this_.examineForm.status;
            this_.utils.request.updateOrderDeliveryReleaseRelation(
              params,
              function(res) {
                if (res.code == "0000") {
                  this_.$message({ message: "操作成功", type: "success" });
                } else {
                  this_.$message({
                    message: "操作失败, " + res.msg,
                    type: "error"
                  });
                }
                this_.examineDialogVisible = false;
                this_.editLoading = false;
              }
            );
          });
        }
      });
    },
    //格式化类型
    formatterType: function(row, column, cellValue) {
      if (cellValue == 1) {
        return "购买";
      } else if (cellValue == 2) {
        return "卖出";
      }
    },
    //审核
    examine: function(row) {
      this.examineDialogVisible = true;
      this.examineForm.id = row.id;
    },
    submitSellBuyForm: function() {
      let this_ = this;
      this_.$refs.sellBuyForm.validate(valid => {
        if (valid) {
          this_.$confirm("确认提交吗？", "提示", {}).then(() => {
            this_.editLoading = true;
            let params = {};
            params.orderNo = this_.sellBuyForm.orderNo;
            params.buyId = this_.sellBuyForm.buyId;
            params.sellId = this_.sellBuyForm.sellId;
            let productNum = 0;
            let buyPrice = 0;
            let sellPrice = 0;
            this_.tableSellBuyData.forEach(item => {
              productNum += Number(item.goodsNum);
              buyPrice += Number(item.goodsNum) * Number(item.buyPrice);
              sellPrice += Number(item.goodsNum) * Number(item.sellPrice);
            });
            params.productNum = productNum;
            params.buyPrice = buyPrice;
            params.sellPrice = sellPrice;
            if (this_.activeName == "first") {
              params.type = 2;
            } else if (this_.activeName == "second") {
              params.type = 1;
            }
            this_.utils.request.saveOrderDeliveryReleaseRelation(
              params,
              function(res) {
                if (res.code == "0000") {
                  this_.$message({ message: "操作成功", type: "success" });
                } else {
                  this_.$message({
                    message: "操作失败, " + res.msg,
                    type: "error"
                  });
                }
                this_.sellBuyDialogVisible = false;
                this_.editLoading = false;
              }
            );
          });
        }
      });
    },
    //买
    buy: function(row) {
      let this_ = this;
      let flag = true;
      this_.sellBuyForm.sellId = row.merchantId;
      this_.sellBuyForm.orderNo = row.orderNo;
      this_.findProduct(row.orderNo);
      this_.tableSellBuyData = [];
      if (flag) {
        this_.tableProductData.forEach(item => {
          let obj = {};
          obj.goodsName = item.goodsName;
          obj.goodsImgUrl = item.goodsImgUrl;
          obj.sellPrice = item.buyUnitPrice;
          obj.buyPrice = item.buyUnitPrice;
          obj.goodsNum = item.goodsNum;
          this_.tableSellBuyData.push(obj);
        });
        flag = false;
      }
      if (!flag) {
        this_.sellBuyDialogVisible = true;
      }
    },
    //卖
    sell: function(row) {
      let this_ = this;
      let flag = true;
      this_.sellBuyForm.buyId = row.merchantId;
      this_.sellBuyForm.orderNo = row.orderNo;
      this_.findProduct(row.orderNo);
      this_.tableSellBuyData = [];
      if (flag) {
        this_.tableProductData.forEach(item => {
          let obj = {};
          obj.goodsName = item.goodsName;
          obj.goodsImgUrl = item.goodsImgUrl;
          obj.sellPrice = item.buyUnitPrice;
          obj.buyPrice = item.buyUnitPrice;
          obj.goodsNum = item.goodsNum;
          this_.tableSellBuyData.push(obj);
        });
        flag = false;
      }
      if (!flag) {
        this_.sellBuyDialogVisible = true;
      }
    },
    //订单编号切换
    changeOrder: function() {
      let this_ = this;
      if (this_.dataForm.orderNo != "") {
        this_.findProduct(this_.dataForm.orderNo);
      }
    },
    //查询订单下的产品
    findProduct: function(data) {
      let this_ = this;
      let param = {};
      param.orderNo = data;
      this.utils.request.queryOrderGoodsByOrderNo(param, function(res) {
        if (res.code == "0000") {
          this_.tableProductData = res.data;
        } else {
        }
      });
    },
    //提交
    submitForm: function() {
      let this_ = this;
      if (this_.tableProductData.length == 0) {
        this_.$message({ message: "请检查订单号是否正确", type: "info" });
        return false;
      }
      this_.$refs.dataForm.validate(valid => {
        if (valid) {
          this_.$confirm("确认提交吗？", "提示", {}).then(() => {
            this_.editLoading = true;
            let params = {};
            params.orderNo = this_.dataForm.orderNo;
            params.type = this_.dataForm.type;
            let productNum = 0;
            let productPrice = 0;
            this_.tableProductData.forEach(item => {
              productNum += Number(item.goodsNum);
              productPrice += Number(item.goodsNum) * Number(item.buyUnitPrice);
            });
            params.productNum = productNum;
            params.productPrice = productPrice;
            this_.utils.request.saveOrderDeliveryRelease(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
              this_.editDialogVisible = false;
              this_.editLoading = false;
              this_.findPage();
            });
          });
        }
      });
    },
    //tab切换
    handleClick: function() {
      if (this.activeName == "second") {
        this.filters.type = 2;
        this.findPage();
      } else if (this.activeName == "first") {
        this.filters.type = 1;
        this.findPage();
      } else {
        this.filters.type = "";
        this.findSellBuyPage();
      }
    },
    // 获取分页数据
    findPage: function(params) {
      let this_ = this;
      if (params == undefined || params == null) {
        params = {
          pageNum: this_.pageRequest.pageNum,
          pageSize: this_.pageRequest.pageSize
        };
      }
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = params.pageNum;
      this_.filters.limit = params.pageSize;
      this.utils.request.queryOrderDeliveryRelease(this_.filters, function(
        res
      ) {
        if (res.data.rows == null) {
          res.data.rows = [];
        }
        this_.pageResult = res.data.rows;
        this_.totalSize = Number(res.data.total);
      });
    },

    // 查询我的订单
    findSellBuyPage: function(params) {
      let this_ = this;
      if (params == undefined || params == null) {
        params = {
          pageNum: this_.pageRequest1.pageNum,
          pageSize: this_.pageRequest1.pageSize
        };
      }
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = params.pageNum;
      this_.filters.limit = params.pageSize;
      this_.filters.status = 1;
      this.utils.request.queryDetailPage(this_.filters, function(res) {
        if (res.data.rows == null) {
          res.data.rows = [];
        }
        this_.pageResult1 = res.data.rows;
        this_.totalSize1 = Number(res.data.total);
      });
    },

    // 显示新增界面
    handleAdd: function() {
      this.editDialogVisible = true;
      this.editLoading = false;
      this.dataForm = {
        orderNo: "",
        type: ""
      };
      this.tableProductData = [];
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 每页数据刷新
    refreshPageRequest: function(pageNum) {
      this.pageRequest.pageNum = pageNum;
      this.findPage(this.pageRequest);
    },
    // 每页条数刷新
    handleSizeChange: function(pageSize) {
      this.pageRequest.pageSize = pageSize;
      this.findPage(this.pageRequest);
    },

    // 重置
    resetForm(formName) {
      this.filters.orderNo = "";
      if (this.activeName == "third") {
        this.findSellBuyPage();
      } else {
        this.findPage();
      }
    }
  }
};
</script>


<style>
</style>

<style scoped lang='scss'>
</style>
